package tree;
import org.junit.Test;

import java.util.*;

/**
 * @Description 102. 二叉树的层序遍历
 * @Author Firenut
 * @Date 2023-01-19 13:53
 * 说白了就是bfs嘛
 */
public class levelOrder {

    @Test
    public void test() {
        TreeNode root = new TreeNode(3);
        TreeNode n1 = new TreeNode(9);
        TreeNode n2 = new TreeNode(20);
        TreeNode n3 = new TreeNode(15);
        TreeNode n4 = new TreeNode(7);
        root.left = n1;
        root.right = n2;
        n2.left = n3;
        n2.right = n4;
        System.out.println(levelOrder(root));
    }

    // 法2:dfs 需要额外的参数index标记结点的层数,往对应层次的list中插入数据即可
    public List<List<Integer>> levelOrder1(TreeNode root) {
        List<List<Integer>> ans=new ArrayList<>();
        if(root==null){
            return ans;
        }
        dfs(ans,0,root);
        return ans;
    }
    // 使用先序、中序、后序都可以,但是必须先左后右,不然满足不了层序
    // 根据索引可以定位, 0表示第0层,1表示第1层 ....
    void dfs(List<List<Integer>>ans,int index,TreeNode node){
        if(ans.size()<index+1){
            ans.add(new ArrayList<>());
        }
        ans.get(index).add(node.val);
        if(node.left!=null){
            dfs(ans,index+1,node.left);
        }
        if(node.right!=null){
            dfs(ans,index+1,node.right);
        }
    }

    // 法1:使用队列 bfs
    public List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> ans = new ArrayList<>();
        Deque<TreeNode> queue = new LinkedList<>(); //也可以用LinkedList
        if(root==null){
            return ans;
        }
        queue.addLast(root);
        while (!queue.isEmpty()) {
            List<Integer> list = new ArrayList<>();
            int size = queue.size();
            for (int i = 0; i < size; i++) {
                TreeNode node = queue.removeFirst(); //队头元素出队
                list.add(node.val); //记录到列表中
                // 左右结点入队
                if (node.left != null) {
                    queue.addLast(node.left);
                }
                if (node.right != null) {
                    queue.addLast(node.right);
                }
            }
            ans.add(list);
        }
        return ans;
    }

}

class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;

    public TreeNode() {
    }

    public TreeNode(int val) {
        this.val = val;
    }

    public TreeNode(int val, TreeNode left, TreeNode right) {
        this.val = val;
        this.left = left;
        this.right = right;
    }
}